package com.XML.Dom4J;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

/**
 *XML案例实战：将XML文件中的联系人数据封装成List集合，其中每个元素是实体类Contact
 *     <contact id="1" vip="true">
 *         <name>潘金莲</name>
 *         <gender>女</gender>
 *         <email>panpan@itcast.com</email>
 *     </contact>
 */

public class Dom4JHelloWordDemo2 {
    public static void main(String[] args) throws Exception {
        //创建dom4j解析对象
        SAXReader saxReader = new SAXReader();
        //加载XML文件，得到document对象
        InputStream resourceAsStream = Dom4JHelloWordDemo1.class.getResourceAsStream("/com/XML/Dom4J/Contacts.xml");
        Document read = saxReader.read(resourceAsStream);
        //获得根目录对象
        Element root = read.getRootElement();
        //获得根目录下所有contact元素对象
        List<Element> contact = root.elements("contact");
        //新建一个Contact对象集合
        List<Contact>list=new ArrayList<>();

        //遍历contact元素集合，得到元素值
        for (Element element : contact) {
            //新建一个Contact对象
            Contact contact1 = new Contact();
            //获得元素值
            contact1.setId(element.attributeValue("id"));
            contact1.setName(element.elementText("name"));
            contact1.setEmail(element.elementText("email"));
            list.add(contact1);
        }

        for (Contact contact1 : list) {
            System.out.println(contact1);
        }

    }

}
